<template>
  <div class="module-box">
    <div>
      <el-input
        v-model="localQuestion"
        placeholder="请输入投票问题"
        @input="handleInput"
        clearable
      />
    </div>
    <div v-for="(option, index) in localOptions" :key="index" style="margin-top: 10px;">
      <el-input
        v-model="localOptions[index]"
        placeholder="请输入选项"
        @input="handleInput"
        clearable
        style="width: 80%;"
      />
      <el-button
        type="danger"
        icon="el-icon-delete"
        circle
        @click="removeOption(index)"
        style="margin-left: 10px;"
      />
    </div>
    <el-button
      type="primary"
      plain
      icon="el-icon-plus"
      style="margin-top: 10px;"
      @click="addOption"
    >
      添加选项
    </el-button>
  </div>
</template>

<script>
export default {
  name: 'VoteModule',
  props: ['module'],
  data() {
    return {
      localQuestion: this.module.props.question || '',
      localOptions: this.module.props.options ? [...this.module.props.options] : [],
    }
  },
  watch: {
    // 同步外部props变化
    'module.props.question'(val) {
      this.localQuestion = val
    },
    'module.props.options'(val) {
      this.localOptions = val ? [...val] : []
    }
  },
  methods: {
    handleInput() {
      const updatedModule = {
        ...this.module,
        props: {
          ...this.module.props,
          question: this.localQuestion,
          options: [...this.localOptions],
        },
      }
      this.$emit('update-module', updatedModule)
    },
    addOption() {
      this.localOptions.push('')
      this.handleInput()
    },
    removeOption(index) {
      this.localOptions.splice(index, 1)
      this.handleInput()
    },
  },
}
</script>

<style scoped>
.module-box {
  padding: 10px;
  border: 1px solid #ddd;
}
</style>
